<template>
    <!-- 基础组件-文本 -->
    <div class="design-text" :style="{
        'margin-top': `${element.options.margin.top}px`,
        'margin-left': `${element.options.margin.left}px`,
        'margin-right': `${element.options.margin.right}px`,
        'margin-bottom': `${element.options.margin.bottom}px`,
        'padding-top': `${element.options.padding.top}px`,
        'padding-left': `${element.options.padding.left}px`,
        'padding-right': `${element.options.padding.right}px`,
        'padding-bottom': `${element.options.padding.bottom}px`
    }">
        <div :style="{
                'font-size': element.style.fontSize,
                'line-height': `${element.style.lineHeight}pt`,
                'letter-spacing': `${element.options.letterSpacing}px`,
                'transform': `scale(${element.options.scale.x}, ${element.options.scale.y})`,
                'text-align': `${element.options.textAlign ? 'justify' : 'initial'}`,
                'text-align-last': `${element.options.textAlignLast ? 'justify' : 'initial'}`
            }"
            class="design-edit"
            ref="designEdit"
            :contenteditable="element.options.edit"
            spellcheck="false"
            @input="inputChange">
        </div>
    </div>
</template>

<script>
import { warning } from '@/utils/errorInfo';
import Observer from "@/utils/eventBus.js";
import { getUUID } from "@/utils/index";
export default {
    name: "DesignText",
    props: {
        element: {
            type: Object
        }
    },
    data() {
        return {
            editor: null, // 编辑器元素
            field: "" // 自动生成一个ID 用于重置光标位置
        }
    },
    methods: {
        init() { // 准备监听选中文字
            // 编辑器dom元素
            this.editor = this.$refs.designEdit;
            // 工具栏的功能
            Observer.$on('designTool', this.designTextTool);
            // 回显数据
            this.editor.innerHTML = this.element.options.contentHTML;
        },
        designTextTool(data) { // 工具栏
            if (data.id !== this.element.id) return; // 只有当前选中的组件才需要处理事件
            if (data.eventType === 'color') { // 颜色事件
                this.ExecCommand('foreColor', data.data);
            } else if (data.eventType === 'bold') { // 加粗
                this.ExecCommand('bold', null);
            } else if (data.eventType === 'italic') { // 斜体
                this.ExecCommand('italic', null);
            } else if (data.eventType === 'underline') { // 下划线
                this.ExecCommand('underline', null);
            } else if (data.eventType === 'strikeThrough') { // 删除线
                this.ExecCommand('strikeThrough', null);
            } else if (data.eventType === 'undo') {
                this.ExecCommand('undo', null);
            } else if (data.eventType === 'redo') {
                this.ExecCommand('redo', null);
            } else if (data.eventType == 'fontName') {
                this.ExecCommand('fontName', data.data);
            } else if (data.eventType == 'fontSize') { // 特殊情况！！
                this.element.style.fontSize = data.data;
            } else if (data.eventType == 'justifyLeft') {
                this.ExecCommand('justifyLeft', null);
            } else if (data.eventType == 'justifyCenter') {
                this.ExecCommand('justifyCenter', null);
            } else if (data.eventType == 'justifyRight') {
                this.ExecCommand('justifyRight', null);
            } else if (data.eventType == 'indent') {
                this.ExecCommand('indent', null);
            } else if (data.eventType == 'outdent') {
                this.ExecCommand('outdent', null);
            } else if (data.eventType == 'lineHeight') { // 特殊情况！！
                this.element.style.lineHeight = data.data;
            }
        },
        ExecCommand(attr, value) { // 使用 execCommand 完成简易编辑器
            document.execCommand(attr, false, value);
        },
        inputChange(e) { // # attr # 输入绑定字段自动生成标签处理
            const target = e.target;
            // 处理 # attr # 情况
            // e.inputType == 'insertCompositionText' || e.inputType == 'insertText'
            if (e.inputType == 'insertFromPaste' || e.inputType == 'insertCompositionText' || e.inputType == 'insertText') {
                let innerHTML = target.innerHTML || '';
                if (/#(.*)#/.test(innerHTML)) {
                    this.field = getUUID();
                    let newHTML = innerHTML.replace(/(.*)#(.*)#(.*)/, `
                        $1
                            <span contenteditable="fasle" class='field-dom' title='$2'>$2</span>
                            <span field=${this.field}></span>
                        $3`);
                    this.editor.innerHTML = newHTML;
                    this.resetCursor();
                }
            }
            this.element.options.contentHTML = this.editor.innerHTML || '';
        },
        resetCursor() { // 生成 tag 重制光标位置
            this.$nextTick(() => {
                const childNodes = this.editor.childNodes || [];
                let node = this.selectNode(childNodes);
                node.innerHTML = '&ZeroWidthSpace;'; // 空白占位符
                node.removeAttribute('field');
                const range = document.createRange();
                range.selectNode(node);
                range.collapse();
                const selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(range);
            })
        },
        selectNode(childNodes) { // 递归查找插入的node节点
            let node = null;
            const recursion = (childNodes) => {
                childNodes.forEach(item => {
                    if ((item.getAttribute && item.getAttribute('field')) == this.field) {
                        node = item;
                    } else {
                        if (item.childNodes && item.childNodes.length > 0) recursion(item.childNodes);
                    }
                })
            }
            recursion(childNodes);
            return node;
        }
    },
    mounted() {
        this.init();
    }
}
</script>

<style>
    .design-text {
        font-size: 14px;
    }
    .design-text .design-edit {
        min-height: 20px;
    }
    blockquote {
        margin: 0 0 0 0 !important;
        text-indent: 2em !important;
    }
    .design-text .field-dom {
        background-color: #ecf5ff;
        display: inline-block;
        /* color: #409eff; */
        border: 2px solid #d9ecff;
        border-radius: 5px;
        box-sizing: border-box;
        white-space: nowrap;
        padding: 0 5px;
        max-width: 130px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        vertical-align: middle;
        text-indent: 0;
    }
</style>